<template>
  <div class="box-shadow pad10">
    <!-- <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="菜单名称" prop="Name">
        <el-input
          v-model="queryParams.Name"
          placeholder="请输入菜单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="CirclePlusFilled" @click="handleAdd"
          >添加</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      :data="menuList"
      row-key="id"
      :border="true"
      :default-expand-all="isExpandAll"
    >
      <el-table-column
        prop="Name"
        label="菜单名称"
        :show-overflow-tooltip="true"
        width="160"
      >
        <template v-slot="{ row }">
          {{ row.meta.title }}
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标" :align="'center'">
        <template v-slot="{ row }">
          <svg-icon :icon-class="row.meta.icon" />
        </template>
      </el-table-column>
      <el-table-column
        prop="sort"
        label="排序"
        :align="'center'"
      ></el-table-column>
      <el-table-column
        prop="perms"
        label="权限标识"
        :align="'center'"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{ row }">
          {{ row.code }}
        </template>
      </el-table-column>
      <el-table-column
        prop="component"
        label="组件路径"
        :align="'center'"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="component"
        label="类型"
        :align="'center'"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{ row }">
          <div v-show="row.menuType == 'M'">目录</div>
          <div v-show="row.menuType == 'C'">菜单</div>
          <div v-show="row.menuType == 'F'">按钮</div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        :align="'center'"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            type="text"
            icon="CirclePlusFilled"
            v-if="scope.row.menuType != 'F'"
            @click="handleAdd(scope.row)"
            style="color: #67c23a"
            >添加</el-button
          >
          <el-popconfirm
            title="确认删除吗？"
            @confirm="handleDelete(scope.row)"
          >
            <template #reference>
              <el-button type="text" icon="Delete" style="color: red"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body draggable>
      <el-form
        ref="menuRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="wid100"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <el-tree-select
                v-model="form.Pid"
                :data="menuOptions"
                :props="{
                  value: 'id',
                  label: 'ownName',
                  children: 'children',
                }"
                value-key="id"
                placeholder="选择上级菜单"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.menuType != 'F'">
            <el-form-item label="菜单图标" prop="Icon">
              <el-popover
                placement="bottom-start"
                :width="540"
                v-model:visible="showChooseIcon"
                trigger="click"
                clearable
                @show="showSelectIcon"
              >
                <template #reference>
                  <el-input
                    v-model="form.Icon"
                    placeholder="点击选择图标"
                    @click="showSelectIcon"
                    v-click-outside="hideSelectIcon"
                    clearable
                  >
                    <template #prefix>
                      <svg-icon
                        v-if="form.Icon"
                        :icon-class="form.Icon"
                        class="el-input__icon"
                        style="height: 32px; width: 16px"
                      />
                      <el-icon v-else style="height: 32px; width: 16px"
                        ><search
                      /></el-icon>
                    </template>
                  </el-input>
                </template>
                <icon-select ref="iconSelectRef" @selected="selected" />
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="Name">
              <el-input v-model="form.Name" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item label="显示排序" prop="Sort">
              <el-input-number
                v-model="form.Sort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item prop="Path">
              <template #label>
                <span>
                  <el-tooltip
                    content="访问的路由地址，如：`user`"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  路由地址
                </span>
              </template>
              <el-input v-model="form.Path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item prop="Path">
              <template #label>
                <span>
                  <el-tooltip content="访问的路由地址，如：`/`" placement="top">
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  重定向
                </span>
              </template>
              <el-input
                v-model="form.Redirect"
                placeholder="请输入重定向地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'F'">
            <el-form-item prop="Component">
              <template #label>
                <span>
                  <el-tooltip
                    content="访问的组件路径，如：`system/user/index`，默认在`views`目录下"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  组件路径
                </span>
              </template>
              <el-input v-model="form.Component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-input
                v-model="form.Code"
                placeholder="请输入权限标识"
                maxlength="100"
              />
              <template #label>
                <span>
                  <el-tooltip
                    content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  编号
                </span>
              </template>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item>
              <el-input
                v-model="form.query"
                placeholder="请输入路由参数"
                maxlength="255"
              />
              <template #label>
                <span>
                  <el-tooltip
                    content="访问路由的默认传递参数，如：`{id: 1}`"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  路由参数
                </span>
              </template>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="是否启用" prop="Enable">
              <el-radio-group v-model="form.Enable">
                <el-radio label="Y">启用</el-radio>
                <el-radio label="N">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item>
              <template #label>
                <span>
                  <el-tooltip
                    content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
                    placement="top"
                  >
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  是否缓存
                </span>
              </template>
              <el-radio-group v-model="form.isCache">
                <el-radio label="0">缓存</el-radio>
                <el-radio label="1">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Menu">
import {
  addMenus,
  editMenus,
  deleteMenus,
  addButtons,
  editButtons,
  deleteButtons,
  getAllMenus,
  getAllButtons,
} from "@/api/system/menu";
import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";
import { ClickOutside as vClickOutside } from "element-plus";
import { onMounted, inject } from "vue";
import usePermissionStore, {
  formatMenu,
  menusWithButton,
} from "@/store/modules/permission.js";
const { proxy } = getCurrentInstance();
const reload = inject("reload");
const menuList = ref([]);
const open = ref(false);
const showSearch = ref(true);
const title = ref("");
const menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const showChooseIcon = ref(false);
const iconSelectRef = ref(null);
const menuStore = usePermissionStore();

const data = reactive({
  form: {
    Enable: "Y",
    Redirect: "/",
  },
  queryParams: {
    Name: undefined,
    visible: undefined,
  },
  rules: {
    Name: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
    Sort: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
    Path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);
onMounted(() => {
  getList();
});

/** 查询菜单列表 */
async function getList() {
  try {
    let res = await getAllMenus({ Code: "", Name: "" });
    let list = formatMenu(res.data);
    let listWithBtn = menusWithButton(list, usePermissionStore().allBtns);
    menuList.value = listWithBtn;
    menuOptions.value = [];
    const menu = { id: "0", ownName: "主类目", children: [] };
    menu.children = JSON.parse(JSON.stringify(menuList.value));
    menuOptions.value.push(menu);
  } catch (error) {
    console.log(error);
  }
}

/** 查询菜单下拉树结构 */
function getTreeselect() {
  // listMenu().then((response) => {
  //   const menu = { menuId: 0, Name: "主类目", children: [] };
  //   // menu.children = proxy.handleTree(response.data, "menuId");
  //   menu.children = JSON.parse(JSON.stringify(menuStore.activeMenus));
  //   menuOptions.value.push(menu);
  // });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    ID: undefined,
    Pid: "0",
    Name: undefined,
    Icon: undefined,
    menuType: "M",
    Sort: undefined,
    Component: "",
    Path: "",
    Enable: "Y",
    Code: "",
    Redirect: "/",
  };
  proxy.resetForm("menuRef");
}
/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
  showChooseIcon.value = true;
}
/** 选择图标 */
function selected(name) {
  form.value.Icon = name;
  showChooseIcon.value = false;
}
/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon(event) {
  var elem =
    event.relatedTarget ||
    event.srcElement ||
    event.target ||
    event.currentTarget;
  var className = elem.className;
  if (className !== "el-input__inner") {
    showChooseIcon.value = false;
  }
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  console.log(row);
  if (row != null && row.id) {
    form.value.Pid = row.id;
    if (row.menuType == "M") {
      form.value.menuType = "C";
      form.value.Component = "Layout";
      form.value.Icon = "bug";
      form.value.Sort = 1;
    }
    if (row.menuType == "C") {
      form.value.menuType = "F";
      form.value.Code = row.code + ":";
    }
  } else {
    form.value.Pid = "0";
  }
  open.value = true;
  title.value = "添加菜单";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
async function handleUpdate(row) {
  console.log(row);
  reset();
  form.value = {
    ID: row.id,
    Pid: row.pid,
    Name: row.ownName,
    Icon: row.meta.icon,
    menuType: row.menuType,
    Sort: row.sort,
    Component: row.component,
    Path: row.path,
    Enable: row.enable,
    Code: row.code,
    Redirect: row.redirect,
  };

  // await getTreeselect();
  // getMenu(row.menuId).then((response) => {
  //   form.value = response.data;
  open.value = true;
  title.value = "修改菜单";
  // });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["menuRef"].validate((valid) => {
    if (valid) {
      if (form.value.ID != undefined) {
        if (form.value.menuType == "F") {
          let query = {
            ID: form.value.ID,
            ID_Menu: form.value.Pid, //菜单的ID
            Code: form.value.Code,
            Name: form.value.Name,
            Enable: form.value.Enable, //是否启用 Y:启用 N:停用
          };
          editButtons(query).then((response) => {
            if (response.status === 0) {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            }
          });
        } else {
          editMenus(form.value).then((response) => {
            if (response.status === 0) {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            }
          });
        }
      } else {
        if (form.value.menuType == "F") {
          let query = {
            ID_Menu: form.value.Pid, //菜单的ID
            Code: form.value.Code,
            Name: form.value.Name,
            Enable: form.value.Enable, //是否启用 Y:启用 N:停用
          };
          addButtons(query).then((response) => {
            if (response.status === 0) {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            }
          });
        } else {
          addMenus(form.value).then((response) => {
            if (response.status === 0) {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            }
          });
        }
      }
    }
  });
}
/** 删除按钮操作 */
async function handleDelete(row) {
  console.log(row);
  try {
    if (row.menuType == "F") {
      await deleteButtons({ ID: row.id });
    } else {
      await deleteMenus({ ID: row.id });
    }
    proxy.$modal.msgSuccess("删除成功");
    getList();
  } catch (error) {
    console.log(error);
  }
}
</script>
